/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mol.market.common.widget;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.mol.market.R;
import com.mol.market.common.util.Utils;

/**
 *
 * 延迟加载Fragment。
 *
 * Author: Andrew.Wang
 * Date  : 12-11-13
 */
public abstract class LazyLoadListFragment extends SherlockFragment implements
    View.OnClickListener {

    /**
     * 每页加载项目数量。<br>
     * 默认值是20项。
     */
    private int mItemsPerPage = 20;

    /**
     * 分页加载当前页数。<br>
     * 注意是从第一页开始。
     */
    private int mPage = 1;

    /**
     * 数据集总条目数。
     */
    private int mTotalSize;

    /**
     * 数据总条目数已经设置。
     */
    private boolean mHasTotalSize;

    /**
     * 异步任务是否正在进行。
     */
    private boolean mIsTaskActive;

    /**
     * 正常加载提示视图
     */
    private View mLoadingView;

    /**
     * 正常加载进度条
     */
    private ProgressBar mLoadingProgressBar;

    /**
     * 正常加载提示信息
     */
    private TextView mLoadingHint;

    /**
     * 延迟加载提示视图
     */
    private View mFooterView;

    /**
     * 延迟加载进度条
     */
    private ProgressBar mFooterProgressBar;

    /**
     * 延迟加载提示信息
     */
    private TextView mFooterHint;

    /**
     * Root
     */
    private View mRootView;

    /**
     * 列表
     */
    protected ListView mListView;

    /**
     * Adapter
     */
    protected LazyLoadListAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        // 开始首次加载
        lazyLoad();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        mRootView = initLayout(inflater, container, savedInstanceState);

        if (mListView == null) {
            mListView = (ListView) mRootView.findViewById(android.R.id.list);

            if (mListView == null) {
                throw new IllegalStateException("There should be a ListView which ID is android.R.id.list");
            }
        }
        initLoadingView();
        mListView.setEmptyView(mLoadingView);

        mAdapter = initAdapter();

        initFooterView();
        mListView.addFooterView(mFooterView, null, false);
        mListView.setAdapter(mAdapter);

        return mRootView;
    }

    @Override
    public void onPause() {
        Utils.D("onPause --->");
        super.onPause();
    }

    @Override
    public void onDetach() {
        Utils.D("onDetach --->");
        super.onDetach();
    }

    @Override
    public void onStop() {
        Utils.D("onStop --->");
        super.onStop();
        reset();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onDestroy() {
        Utils.D("onDestroy --->");
        mLoadingView = null;
        mLoadingProgressBar = null;
        mLoadingHint = null;
        mFooterView = null;
        mFooterProgressBar = null;
        mFooterHint = null;
        mListView = null;
        mAdapter = null;
        super.onDestroy();
    }

    // ----------------------------------------------------------------------
    /**
     * 初始化页面布局。</br>
     * 注意：使用的ListView的id必须是{@android:id/list}
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     */
    protected abstract View initLayout(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState);

    /**
     * 初始化ListAdapter。
     */
    protected abstract LazyLoadListAdapter initAdapter();

    /**
     * 加载数据。
     */
    protected abstract void load();

    // ----------------------------------------------------------------------

    /**
     * 设置数据集总条目数。
     */
    public void setTotalSize(int totalSize) {
        this.mTotalSize = totalSize;
        this.mHasTotalSize = true;
    }

    /**
     * 是否设置总大小
     */
    public boolean hasTotalSize() {
        return this.mHasTotalSize;
    }

    /**
     * 获取数据的总条目数。
     */
    public int getTotalSize() {
        return this.mTotalSize;
    }

    /**
     * 获取分页加载数据当前页的起始下标。
     */
    public int getStartPosition() {
        return mItemsPerPage * (mPage - 1);
    }

    /**
     * 获取分页加载数据当前页的终止下标
     */
    public int getEndPosition() {
        return getStartPosition() + mItemsPerPage;
    }

    /**
     * 设置每页的项目数
     */
    public void setItemsPerPage(int num) {
        mItemsPerPage = num;
    }

    /**
     * 获取每页的项目数
     */
    public int getItemsPerPage() {
        return mItemsPerPage;
    }

    /**
     * 获取当前分页
     */
    public int getCurrentPage() {
        return mPage;
    }

    /**
     * 是否当前为首次加载
     */
    public boolean isFirstPageLoad() {
        return mPage == 1;
    }

    /**
     * 异步加载成功，如果没有更多的数据则移除底部加载视图。
     */
    public void loadSuccess() {
        mIsTaskActive = false;

        if (isFirstPageLoad()) {
            // show the lazy load indicator
            mFooterView.setVisibility(View.VISIBLE);
        }

        mPage++;

        if (!hasMore()) {
            mListView.removeFooterView(mFooterView);
        }
    }

    /**
     * 异步加载失败，显示重试提示。
     */
    public void loadFailure() {
        mIsTaskActive = false;

        if (mPage == 1) {
            // 首页加载失败
            mLoadingProgressBar.setVisibility(View.GONE);
            mLoadingHint.setVisibility(View.VISIBLE);
        } else {
            // 分页加载失败
            mFooterProgressBar.setVisibility(View.GONE);
            mFooterHint.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 通过这个方法告诉Adapter是否还有更多数据可以加载。
     */
    public boolean hasMore() {
        return (mItemsPerPage * mPage) < mTotalSize;
    }

    /**
     * 异步加载数据。
     */
    public void lazyLoad() {

        if (mIsTaskActive) {
            // 同时只允许一个异步任务
            return;
        }

        mIsTaskActive = true;
        load();
    }

    /**
     * 重置加载页
     */
    public void reset() {
        mPage = 1;
    }

    @Override
    public void onClick(View v) {

        int id = v.getId();
        if (id == R.id.f_no_data) {
            mFooterProgressBar.setVisibility(View.VISIBLE);
            mFooterHint.setVisibility(View.GONE);
            lazyLoad();
            return;
        } else if (id == R.id.no_data) {
            mLoadingProgressBar.setVisibility(View.VISIBLE);
            mLoadingHint.setVisibility(View.GONE);
            lazyLoad();
            return;
        }
    }

    /**
     * 初始化加载提示信息。</br>
     *
     * 注意：EmptyView必须和ListView同级才能被正常显示。
     */
    private void initLoadingView() {
        mLoadingView = mRootView.findViewById(R.id.loading);
        mLoadingView.setBackgroundResource(R.drawable.list_item_bg_selector);
        mLoadingProgressBar = (ProgressBar) mLoadingView.findViewById(R.id.progressbar);
        // TODO fix this loading drawable
        mLoadingProgressBar.setIndeterminateDrawable(new LoadingDrawable(getActivity()));
        mLoadingHint = (TextView) mLoadingView.findViewById(R.id.no_data);
        mLoadingHint.setOnClickListener(this);
    }

    /**
     * 初始化底部延迟加载提示信息
     */
    private void initFooterView() {
        LayoutInflater inflater = (LayoutInflater)
            getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mFooterView = inflater.inflate(R.layout.footer_loading, mListView, false);
        mFooterView.setBackgroundResource(R.drawable.list_item_bg_selector);
        mFooterProgressBar = (ProgressBar) mFooterView.findViewById(R.id.f_progressbar);
        // TODO fix this loading drawable
        mFooterProgressBar.setIndeterminateDrawable(new LoadingDrawable(getActivity()));
        mFooterHint = (TextView) mFooterView.findViewById(R.id.f_no_data);
        mFooterHint.setOnClickListener(this);
        mFooterView.setVisibility(View.GONE);
    }

//    @Override
//    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//
//        HashMap<String, Object> item = (HashMap<String, Object>) mAdapter
//                .getItem(position - mListView.getHeaderViewsCount());
//        String pid = (String) item.get(Constants.KEY_PRODUCT_ID);
//        String name = (String) item.get(Constants.KEY_PRODUCT_NAME);
//        Intent detailIntent = new Intent(getActivity(), ProductDetailActivity.class);
//        detailIntent.putExtra(Constants.EXTRA_PRODUCT_ID, pid);
//        detailIntent.putExtra(Constants.EXTRA_SOURCE_TYPE, Constants.SOURCE_TYPE_GFAN);
//        detailIntent.putExtra(Constants.EXTRA_PRODUCT_NAME, name);
//        getActivity().startActivity(detailIntent);
//    }
}
